#include "SqlInterface.h"


bool SqlInterface::addConnectDB()
{
    QString settingsFileName = "dbsettings.cfg";
    TaskUtils::createSettingsFile(settingsFileName);

    QString baseType = TaskUtils::iniFileRead(settingsFileName, "Connection", "DatabaseType").toString();
    QString hostName = TaskUtils::iniFileRead(settingsFileName, "Connection", "HostName").toString();
    QString dataBase = TaskUtils::iniFileRead(settingsFileName, "Connection", "Database").toString();
    int port = TaskUtils::iniFileRead(settingsFileName, "Connection", "Port").toInt();
    QString userName = TaskUtils::iniFileRead(settingsFileName, "Connection", "UserName").toString();
    QString password = TaskUtils::iniFileRead(settingsFileName, "Connection", "Password").toString();

    QSqlDatabase db = QSqlDatabase::addDatabase(baseType);
    db.setHostName(hostName);
    db.setDatabaseName(dataBase);
    db.setPort(port);
    db.setUserName(userName);
    db.setPassword(password);

    if (!db.open()) {
        QString dbError = db.lastError().text();
        QString msgText = QObject::tr("Ошибка подключения к базе данных. ");
        if (dbError.contains("fe_sendauth: no password supplied"))
            msgText += QObject::tr("Не задано имя пользователя и/или пароль.");
        else if (dbError.contains(QRegExp("FATAL:  Password authentication failed for user \".*\"")))
            msgText += QObject::tr("Неверное имя пользователя и/или пароль.");
        else if (dbError.contains(QRegExp("could not translate host name \".*\" to address: Unknown host")))
            msgText += QObject::tr("Неверное имя сервера: ") + db.hostName();
        else if (dbError.contains(QRegExp("could not connect to server: Connection refused")))
            msgText += QObject::tr("Невозможно подключиться к серверу БД: ") + db.hostName();
        else if (dbError.contains(QRegExp("FATAL:  database \".*\" does not exist")))
            msgText += QObject::tr("Неверное имя базы данных: ") + db.databaseName();
        else if (dbError.contains("Driver not loaded", Qt::CaseInsensitive))
            msgText += QObject::tr("Не найден драйвер базы данных.");
        else
            msgText += dbError;

        qDebug() << msgText;
        return false;
    }

    return true;
}

bool SqlInterface::addConnectDBMemory()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(":memory:");
    if (!db.open()) {
        qDebug() << "Cannot open database" << "Unable to establish a database connection.\n"
                    "This application needs SQLite support. Please read "
                    "the Qt SQL driver documentation for information how "
                    "to build it.\n\n"
                    "Click Cancel to exit.";
        return false;
    }

    return true;
}

void SqlInterface::removeConnectDB(const QString &connectionName)
{
    QSqlDatabase db = QSqlDatabase::database(connectionName);
    if (db.isValid()) {
        db.close();
        QSqlDatabase::removeDatabase(connectionName);
    }
}

bool SqlInterface::createDB()
{
    QSqlQuery query;
    query.exec("CREATE TABLE event ( "
               "id         INTEGER PRIMARY KEY AUTOINCREMENT, "
               "format     VARCHAR, "
               "occur      VARCHAR, "
               "name       VARCHAR( 50 ), "
               "definition VARCHAR, "
               "image      VARCHAR, "
               "icon       VARCHAR, "
               "color      VARCHAR "
               "); ");
    if (query.lastError().isValid()) {
        qDebug() << query.lastError();
        return false;
    }
    query.exec("CREATE UNIQUE INDEX event_id ON event ( id COLLATE NOCASE ASC );");
    if (query.lastError().isValid()) {
        qDebug() << query.lastError();
        return false;
    }

    query.exec("CREATE UNIQUE INDEX event_event ON event ( "
               "format, "
               "name, "
               "occur "
               "); ");
    if (query.lastError().isValid()) {
        qDebug() << query.lastError();
        return false;
    }

    return true;
}

bool SqlInterface::fillDB()
{
    QSqlQuery query;
    query.exec("INSERT INTO event VALUES(null, "
               "'YYYYMMDD', "
               "'20110707', "
               "'event 07 july', "
               "'event 07 july text', "
               "'holiday.png', "
               "'icon_birthday.png', "
               "'')");
    if (query.lastError().isValid()) {
        qDebug() << query.lastError();
        return false;
    }

    query.exec("INSERT INTO event VALUES(null, "
               "'YYYYMMDD', "
               "'20110707', "
               "'Maxs Birthday', "
               "'text piu piu', "
               "'max_power.jpg', "
               "'icon_birthday.png', "
               "'')");
    if (query.lastError().isValid()) {
        qDebug() << query.lastError();
        return false;
    }

    query.exec("INSERT INTO event VALUES(null, "
               "'YYYYMMDD', "
               "'20110707', "
               "'Piu piu piu piu', "
               "'text piu piu 2', "
               "'holiday.png', "
               "'icon_holiday.png', "
               "'')");
    if (query.lastError().isValid()) {
        qDebug() << query.lastError();
        return false;
    }

    query.exec("INSERT INTO event VALUES(null, "
               "'YYYYMMDD', "
               "'20110707', "
               "'Trololololooollooooololo', "
               "'text Trololololooollooooololo', "
               "'holiday.png', "
               "'icon_holiday.png', "
               "'')");
    if (query.lastError().isValid()) {
        qDebug() << query.lastError();
        return false;
    }

    query.exec("INSERT INTO event VALUES(null, "
               "'YYYYMMDD', "
               "'20110707', "
               "'unz unz unz unz', "
               "'text unz unz Trololololooollooooololo', "
               "'holiday.png', "
               "'icon_holiday.png', "
               "'')");
    if (query.lastError().isValid()) {
        qDebug() << query.lastError();
        return false;
    }

    query.exec("INSERT INTO event VALUES(null, "
               "'YYYYMMDD', "
               "'20110707', "
               "'event event 1', "
               "'text unz unz 11 112', "
               "'holiday.png', "
               "'icon_birthday.png', "
               "'')");
    if (query.lastError().isValid()) {
        qDebug() << query.lastError();
        return false;
    }

    query.exec("INSERT INTO event VALUES(null, "
               "'YYYYMMDD', "
               "'20110707', "
               "'event event 2', "
               "'text unz unz 222222', "
               "'holiday.png', "
               "'icon_birthday.png', "
               "'')");
    if (query.lastError().isValid()) {
        qDebug() << query.lastError();
        return false;
    }

    query.exec("INSERT INTO event VALUES(null, "
               "'YYYYMMDD', "
               "'20110705', "
               "'event 05 july', "
               "'event 05 july text', "
               "'holiday.png', "
               "'icon_birthday.png', "
               "'')");
    if (query.lastError().isValid()) {
        qDebug() << query.lastError();
        return false;
    }

    query.exec("INSERT INTO event VALUES(null, "
               "'YYYYMMDD', "
               "'20110708', "
               "'event 08 july', "
               "'event 08 july text', "
               "'svg-logo.svg', "
               "'icon_birthday.png', "
               "'')");
    if (query.lastError().isValid()) {
        qDebug() << query.lastError();
        return false;
    }

    query.exec("INSERT INTO event VALUES(null, "
               "'YYYYMMDD', "
               "'20110708', "
               "'event piu piu', "
               "'piu piu piu piu text', "
               "'svg-logo.svg', "
               "'icon_birthday.png', "
               "'')");
    if (query.lastError().isValid()) {
        qDebug() << query.lastError();
        return false;
    }

    query.exec("INSERT INTO event VALUES(null, "
               "'YYYYMMDDHHmm', "
               "'201107141418', "
               "'event 14 july', "
               "'event 14 july text', "
               "'svg-logo.svg', "
               "'icon_birthday.png', "
               "'')");
    if (query.lastError().isValid()) {
        qDebug() << query.lastError();
        return false;
    }

    query.exec("INSERT INTO event VALUES(null, "
               "'YYYYMMDD', "
               "'20110711', "
               "'conj. event', "
               "'conj. event text', "
               "'holiday.png', "
               "'icon_birthday.png', "
               "'')");
    if (query.lastError().isValid()) {
        qDebug() << query.lastError();
        return false;
    }

    query.exec("INSERT INTO event VALUES(null, "
               "'YYYYMMDDHHmm', "
               "'201107111418', "
               "'other event', "
               "'other event text', "
               "'svg-logo.svg', "
               "'icon_birthday.png', "
               "'')");
    if (query.lastError().isValid()) {
        qDebug() << query.lastError();
        return false;
    }

    return true;
}
